package com.qf.listener;

import com.qf.constatns.RabbitMQConstatns;
import com.qf.vo.Goods;
import com.rabbitmq.client.Channel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class GoodsESQueueListener {

    @Autowired
    private Configuration configuration;

    private String path;

    private Template template;

    @PostConstruct
    public void initPath() throws Exception {
        File file = ResourceUtils.getFile("shop-11-item\\src\\main\\resources\\templates");
        path = file.getAbsolutePath();
        // 2.贮备模板
        template = configuration.getTemplate("goodsItem.ftl");
    }


    @RabbitListener(queues = RabbitMQConstatns.GOODS_ITEM_QUEUE)
    public void addGoodsToEs(Goods goods, Channel channel, Message message) throws IOException {
        try {

            // 3.把多个数据封装到Map中
            Map<String, Object> modelMap = new HashMap<>();
            modelMap.put("gname", goods.getGname());
            modelMap.put("gprice", goods.getGprice());
            modelMap.put("gpngList", goods.getGpng().split("\\|"));

            template.process(modelMap, new FileWriter(path + File.separator + goods.getId() + ".html"));

            // 手动ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("生成item页面出现了异常", e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
